package com.hup.utils.io.socket.netty.view;

import com.hup.utils.io.socket.netty.model.MyLoginData;
import io.netty.channel.Channel;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * @author hugan
 * @date 2021/4/26
 */
public class ClientItem extends JPanel implements ActionListener {
    public JPanel root;
    public JLabel txtClient;
    public JButton btnDisconnect;
    private Channel channel;

    public ClientItem() {
        $$$setupUI$$$();
        btnDisconnect.addActionListener(this);
    }

    private void createUIComponents() {
        root = this;
    }

    /**
     * Method generated by IntelliJ IDEA GUI Designer
     * >>> IMPORTANT!! <<<
     * DO NOT edit this method OR call it in your code!
     *
     * @noinspection ALL
     */
    private void $$$setupUI$$$() {
        createUIComponents();
        root.setLayout(new GridBagLayout());
        txtClient = new JLabel();
        txtClient.setHorizontalAlignment(2);
        txtClient.setText("Label");
        GridBagConstraints gbc;
        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.weightx = 1.0;
        gbc.anchor = GridBagConstraints.WEST;
        root.add(txtClient, gbc);
        btnDisconnect = new JButton();
        btnDisconnect.setText("断开");
        gbc = new GridBagConstraints();
        gbc.gridx = 1;
        gbc.gridy = 0;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        root.add(btnDisconnect, gbc);
    }

    /**
     * @noinspection ALL
     */
    public JComponent $$$getRootComponent$$$() { return root; }

    /**
     * @param loginData nullable
     */
    public void setClient(Channel channel, MyLoginData loginData) {
        this.channel = channel;
        StringBuilder sb = new StringBuilder();
        if (loginData != null) sb.append(loginData.name).append(':');
        sb.append(channel.remoteAddress().toString());
        txtClient.setText(sb.toString());
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        channel.close();
    }
}
